package com.jdbc;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class DBUtil {
	public static BasicDataSource ds;
	static{
		Properties p = new Properties();
		try {
			p.load(DBUtil.class.getClassLoader().getResourceAsStream("com/jdbc/db.properties"));
			//读取连接参数
			String driver = p.getProperty("jdbc.driver");
			String url = p.getProperty("jdbc.url");
			String user = p.getProperty("jdbc.user");
			String password = p.getProperty("jdbc.password");

			ds = new BasicDataSource();
			//设置连接参数(必须设置)
			ds.setDriverClassName(driver);
			ds.setUrl(url);
			ds.setUsername(user);
			ds.setPassword(password);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("加载配置文件失败",e);
		}
		
	}
	
	/**
	 * 创建连接
	 * @return
	 */
	public static synchronized Connection getConnection(){
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("创建连接失败",e);
		}
	}
	
	/**
	 * 关闭连接
	 * @param conn
	 * @param stmt
	 */
	public static void close(Connection conn,Statement stmt){
		try {
			if(conn != null){
				conn.close();
			}
			if(stmt != null){
				stmt.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("释放资源失败",e);
		}
	}
	public static void close(Connection conn,Statement stmt,ResultSet rs){
		try {
			if(rs != null){
				rs.close();
			}
			if(stmt != null){
				stmt.close();
			}
			if(conn != null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("释放资源失败",e);
		}
	}
}
